import {nextFunction, parsedRequest, postFileInfo} from "../finch-core";
import {ServerResponse} from "http";
import {getRandomString} from "finch-tools";
import fs = require("fs");
import path = require("path");
import Busboy = require("busboy");
//TODO: 对于上传文件的限制
//TODO: 整理更新BusBoy的新版本的支持

const uploadPath = './upload'

function postParser(req: parsedRequest, res: ServerResponse, next: nextFunction) {
    if (req.method !== "POST") {
        next();
        return;
    }
    req.postFields = {};
    req.postFiles = [];
    if (!fs.existsSync(uploadPath)) {
        fs.mkdirSync(uploadPath);
    }
    let busboy = Busboy({headers: req.headers});
    busboy.on('file', function (fileName, fileStream, fileInfo) {
        let FN = getRandomString();
        let saveTo = path.join("./upload", FN);
        fileStream.pipe(fs.createWriteStream(saveTo));
        let fi: postFileInfo = {fileName: FN, orgName: fileInfo};
        req.postFiles.push(fi);
    });
    busboy.on('field', function (fieldName, value, fieldInfo) {
        req.postFields[fieldName] = value;
    });
    busboy.on('finish', function () {
        next();
    });
    req.pipe(busboy);
}

export {postParser}